package com.zhdl.network.serialport.analysis;

import cn.hutool.core.util.HexUtil;
import com.project.command.faq.analysis.ComAnalysis;
import com.project.command.faq.analysis.ComAnalysisData;
import com.project.command.faq.analysis.ComAnalysisResult;
import com.zhdl.common.eventbus.center.EventBusCenter;
import com.zhdl.modules.tools.EventBusTag;
import com.zhdl.network.serialport.dto.SerialNormalDto;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service(ModbusAnalysis.SERIAL_NORMAL)
public class ModbusAnalysis implements ComAnalysis<String, ByteBuf> {

    public static final String SERIAL_NORMAL = "serial_normal";

    ByteBuf buf = Unpooled.buffer();// 无限制长度


    /**
     * com原始返回数据,进行解析
     * 将ByteBuf 数据,转换为list初步解析对象
     * 接收示例数据 01 05 00 00 FF 00 8C 3A
     *
     * @param data
     * @return 可能多个数据包
     */
    @Override
    public ComAnalysisResult<String> analysisData(ComAnalysisData<ByteBuf> data) {
        List<String> fullFrames = new ArrayList<>();
        try {
            // 循环读取数据流中的数据，一个字节一个字节的读取
            // mark当前Index，如果无法处理，则重置index，再有数据时仍然从头开始匹配
            buf = data.getBuf();
            buf.markReaderIndex();
            int i = buf.readableBytes();
            if (i<195){
                 return new ComAnalysisResult<>(null);
            }
            int breakCnt = 0;
            while (buf.isReadable()) {
                buf.readBytes(breakCnt);   // 跳过上次循环读的n个字节
                breakCnt++;
                SerialNormalDto modbusDto = new SerialNormalDto();
                // 记录读取Index
                byte[] bytes = new byte[i];
                buf.readBytes(bytes);
                modbusDto.setUnitBuff(bytes);
                modbusDto.setFullBuff(bytes);
                byte[] distance = new byte[2];
                distance[0] = bytes[11];
                distance[1] = bytes[10];

                log.info("测距测量数据:<<<<<<<<<<<"+Integer.valueOf(HexUtil.encodeHexStr(distance),16).shortValue()+"mm");
                int distance1 = Integer.valueOf(HexUtil.encodeHexStr(distance),16).shortValue();
                EventBusTag eventBusTag = new EventBusTag();
                eventBusTag.setTag("distance");
                eventBusTag.setCmd(distance1+"");
                EventBusCenter.getEventBus().post(distance1);
                fullFrames.add(Integer.valueOf(HexUtil.encodeHexStr(distance),16).shortValue()+"mm");

                breakCnt = 0;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            buf.resetReaderIndex();
            //从头开始读
        }
        return new ComAnalysisResult<>(fullFrames);
    }


    /**
     * 获取协议头信息
     *
     * @return
     */
    @Override
    public String getHeadAnalysis() {
        return "";
    }

    /**
     * 协议追加校验位信息（尾部数据）
     *
     * @param cmdStr
     * @return
     */
    @Override
    public byte[] getAfterAnalysis(String cmdStr) {
        return HexUtil.decodeHex(cmdStr);
    }
}
